import Router from 'vue-router'
import store from '@/vuex/store.js'
import util from '@/utils/pro_util'
import components from '@/router/component'


Vue.use(Router);

const router = new Router({
  mode: 'history',
  routes: components
})

//定义一个白名单路由数组

const WHITE_PATH_URL = [];
for (var i = 0; i < components.length; i++) {
  if (components[i].path !== '/home') {
    WHITE_PATH_URL.push(components[i].path);
  }
}

//判断数组中是否包含某元素
var isExit= function(str,array){
  var flag=false;
  for(var i=0;i<array.length;i++){
    if(str==array[i]){
      flag=true;
    }
  }
  return flag;
}

// // console.log("路由白名单为"+WHITE_PATH_URL);

// NProgress.inc(0.2);
// NProgress.configure({
//   minimum: 0.08,
//   easing: 'linear',
//   positionUsing: '',
//   speed: 200,
//   trickle: true,
//   trickleSpeed: 200,
//   showSpinner: false,
//   barSelector: '[role="bar"]',
//   spinnerSelector: '[role="spinner"]',
//   parent: 'body',
//   template: `<div class="bar" role="bar">
//                 <div class="peg"></div>
//                </div>
//                <div class="spinner" role="spinner">
//                 <div class="spinner-icon"></div>
//                </div>`
// })

//校验token是否过期
var validTokenExp =function (){
  return util.base64decode(store.getters.getValForKey("token")).exp > (new Date().getTime());
}

//全局路由前守卫
router.beforeEach((to, from, next) => {
  // // console.log(to);
  // console.log(from);
  // // console.log("登录前的URL"+store.getters.getValForKey("beforeLoginUrl"));
  NProgress.start();
  if (isExit(to.path,WHITE_PATH_URL)) {
    if(to.path=="/login"){
      if (store.getters.getValForKey("token") != null) {
        // //判断本地记录的登录状态是否已经失效；//不需要了
        // if (validTokenExp()) {
        //   // 说明当前token过期时间到了
        //   console.log("token没过期");
        router.replace("/home");
        //   return;
        // } else {
        //   console.log("token过期了");
        //   store.commit("clearToken");
        // }
      }
    }
    next();
    return;
  }
  //判断是否已经登录过
  if (store.getters.getValForKey("token") != null) {
    next();
  }else{
    util.msgWaring('请先登录');
    store.commit("clearToken");
    next("/login");
  }
})

//全局路由解析守卫
router.beforeResolve((to, from, next) => {
  if(to.path!='/login'){
    store.commit("saveBeforeLoginUrl",to.fullPath);
  }
  NProgress.done();
  next();
})
//全局路由后置钩子
router.afterEach((to, from) => {

})

export default router;
